package com.heima.datasync.service.Impl;
import com.heima.datasync.mapper.ApArticleMapper;
import com.heima.datasync.service.EsDataService;
import com.heima.datasync.vo.SearchArticleVo;
import com.heima.es.service.EsService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
@Service
public class EsDataServiceImpl implements EsDataService {
  
    public static final String ARTICLE_INDEX_NAME = "app_info_article";
    @Autowired
    private ApArticleMapper apArticleMapper;
    @Autowired
    private EsService<SearchArticleVo> esService;

  @Override
  public ResponseResult dataInit() {

    // 批量导入数据:
    // 一般建议是1000-5000个文档，如果你的文档很大，可以适当减少队列，大小建议是5-15MB，默认不能超过100M
    //  如果数据库数据过多 建议分段批量插入

    List<ApArticle> apArticleList = apArticleMapper.findAllArticles();
    if (StringUtils.isEmpty(apArticleList)) {
      return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "数据库信息不存在");
    }
    // 遍历页码批量插入到索引库
    ArrayList<SearchArticleVo> list = new ArrayList<>();
    for (ApArticle apArticle : apArticleList) {
      //
      SearchArticleVo searchArticleVo = new SearchArticleVo();
      BeanUtils.copyProperties(apArticle, searchArticleVo);
      searchArticleVo.setLayout(apArticle.getLayout().intValue());
      list.add(searchArticleVo);
    }
    esService.saveBatch(list, ARTICLE_INDEX_NAME);
    return ResponseResult.okResult();
    }
}